
import Vue from 'vue'
import Vuex from 'vuex'

import { getUserInfoApi } from '@/api'
import { getToken, setToken, delToken } from '@/utils/auth.js'
//导入store

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    token: getToken() || {},  //为了防止token不存在而报错
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
        state.token = token
        setToken(token)
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    logout(state) {
      //删除localStorage 的token
      delToken()
      //删除vuex的token, userInfo信息
      state.token = {}
      state.userInfo = {}
    }
  },
  actions: {
    async setUserInfo(context) {
      if(!context.state.userInfo.name) {
        const res = await getUserInfoApi()
        context.commit('setUserInfo', res.data.data)
      }
    }
  }
})



export default store